package org.com.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.com.common.R;
import org.com.mapper.FarmsMapper;
import org.com.pojo.Farms;
import org.com.service.FarmsService;
import org.com.service.UserBalanceService;
import org.com.service.TransactionsService;
import org.com.util.AliOssUtil;
import org.com.vo.FarmApplyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "农场管理")
@RestController
@RequestMapping("/api/farms")
public class FarmsController {
    
    @Autowired
    private AliOssUtil aliOssUtil;
    
    @Autowired
    private FarmsService farmsService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private TransactionsService transactionsService;

    @Autowired
    private FarmsMapper farmsMapper;

    @PostMapping("/create")
    public R addFarm(HttpServletRequest request,
                          @RequestParam String farmName,
                          @RequestParam Double appliedAmount,
                          @RequestParam String farmAddress,
                          @RequestParam String farmDescription,
                          @RequestParam MultipartFile image) {

        log.info("接收到创建农场请求");
        log.info("请求参数: farmName={}, farmAddress={}, appliedAmount={}, farmDescription={}", 
            farmName, farmAddress, appliedAmount, farmDescription);
        log.info("上传的图片信息: name={}, size={}, contentType={}", 
            image.getOriginalFilename(), 
            image.getSize(), 
            image.getContentType());

        try {
            log.info("开始上传图片到OSS...");
            String imageUrl = aliOssUtil.upload(image);
            log.info("图片上传成功，URL: {}", imageUrl);

            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                log.warn("用户未登录，session为空或userId为空");
                return R.error("用户未登录");
            }

            Integer userId = (Integer) session.getAttribute("userId");
            log.info("当前用户ID: {}", userId);

            Farms farm = new Farms();
            farm.setFarmName(farmName);
            farm.setUserId(userId);
            farm.setAppliedSubsidyAmount(appliedAmount);
            farm.setFarmAddress(farmAddress);
            farm.setFarmDescription(farmDescription);
            farm.setStatusId(0); // 初始状态为申请中
            log.info("准备保存农场信息: {}", farm);

            boolean result = farmsService.addFarms(farm, imageUrl);
            log.info("保存农场结果: {}", result);

            if (result) {
                log.info("农场创建成功，farmId: {}", farm.getFarmId());
                return R.success("农场创建成功", farm);
            } else {
                log.warn("农场创建失败");
                return R.error("农场创建失败");
            }
        } catch (Exception e) {
            log.error("创建农场过程中发生异常", e);
            return R.error("创建农场失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public R getUserFarms(HttpServletRequest request) {
        log.info("开始获取用户农场列表");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            log.warn("用户未登录");
            return R.error("用户未登录");
        }

        try {
            Integer userId = (Integer) session.getAttribute("userId");
            log.info("获取用户ID: {}", userId);
            
            List<Farms> farms = farmsService.getUserFarms(userId);
            log.info("查询到农场数量: {}", farms != null ? farms.size() : 0);
            
            if (farms == null || farms.isEmpty()) {
                log.info("用户暂无农场数据");
                return R.success("暂无农场数据");
            }
            
            log.info("成功获取农场列表");
            return R.success("获取农场列表成功", farms);
        } catch (Exception e) {
            log.error("获取农场列表失败", e);
            return R.error("获取农场列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/upload")
    public R upload(@RequestParam MultipartFile image) {
        try {
            String url = aliOssUtil.upload(image);
            return R.success("上传成功", url);
        } catch (Exception e) {
            return R.error("图片上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/apply")
    public R getApplyFarms() {
        try {
            log.info("接收到获取农场申请列表请求");
            List<FarmApplyVO> farms = farmsService.getApplyFarms();
            log.info("成功获取农场申请列表，数量：{}", farms.size());
            for (FarmApplyVO farm : farms) {
                log.info("农场详情 - ID: {}, 名称: {}, 状态: {}, 图片数量: {}", 
                    farm.getFarmId(), 
                    farm.getFarmName(), 
                    farm.getStatusText()

                );
            }
            return R.success("获取农场申请列表成功", farms);
        } catch (Exception e) {
            log.error("获取农场申请列表失败", e);
            return R.error("获取农场申请列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/approve/{farmId}")
    public R approveFarm(@PathVariable Integer farmId, @RequestParam BigDecimal amount, @RequestParam Integer farmUserId, HttpSession session) {
        log.info("开始处理农场审批, farmId: {}, amount: {}, farmUserId: {}", farmId, amount, farmUserId);
        
        // 获取当前管理员ID
        Integer adminUserId = (Integer) session.getAttribute("userId");
        if (adminUserId == null) {
            return R.error("未登录或会话已过期");
        }
        
        try {
            // 1. 获取农场信息
            Farms farm = farmsService.getById(farmId);
            if (farm == null) {
                return R.error("农场不存在");
            }
            
            // 验证前端传来的用户ID与农场所有者ID是否一致
            if (!farmUserId.equals(farm.getUserId())) {
                log.warn("前端传入的用户ID与农场所有者ID不匹配, 前端用户ID: {}, 农场所有者ID: {}", farmUserId, farm.getUserId());
                return R.error("农场所有者信息不匹配");
            }
            
            // 验证前端传来的金额与数据库中的申请金额是否一致
            BigDecimal appliedAmount = BigDecimal.valueOf(farm.getAppliedSubsidyAmount());
            log.info("金额比较 - 前端金额: {}, 数据库金额: {}", amount, appliedAmount);
            
            // 使用compareTo进行比较，避免精度问题
            if (amount.compareTo(appliedAmount) != 0) {
                log.warn("前端传入金额与申请金额不匹配, 前端金额: {}, 申请金额: {}", amount, appliedAmount);
                return R.error("审批金额与申请金额不匹配");
            }
            
            // 2. 获取管理员余额
            BigDecimal adminBalance = userBalanceService.getUserBalance(adminUserId);
            
            // 3. 检查余额是否足够
            if (adminBalance.compareTo(amount) < 0) {
                return R.error("管理员账户余额不足");
            }
            
            // 4. 开始事务处理
            boolean success = farmsService.approveFarmApplication(farmId, adminUserId, farmUserId, amount);
            
            if (success) {
                return R.success("审批通过成功");
            } else {
                return R.error("审批处理失败");
            }
        } catch (Exception e) {
            log.error("农场审批处理失败", e);
            return R.error("审批处理异常：" + e.getMessage());
        }
    }

    @PostMapping("/reject/{farmId}")
    public R rejectFarm(@PathVariable Integer farmId, @RequestParam Integer farmUserId, HttpSession session) {
        log.info("开始处理农场拒绝申请, farmId: {}, farmUserId: {}", farmId, farmUserId);
        
        // 获取当前管理员ID
        Integer adminUserId = (Integer) session.getAttribute("userId");
        if (adminUserId == null) {
            return R.error("未登录或会话已过期");
        }
        
        try {
            // 1. 获取农场信息
            Farms farm = farmsService.getById(farmId);
            if (farm == null) {
                return R.error("农场不存在");
            }
            
            // 验证前端传来的用户ID与农场所有者ID是否一致
            if (!farmUserId.equals(farm.getUserId())) {
                log.warn("前端传入的用户ID与农场所有者ID不匹配, 前端用户ID: {}, 农场所有者ID: {}", farmUserId, farm.getUserId());
                return R.error("农场所有者信息不匹配");
            }
            
            // 更新农场状态为已拒绝(3)
            farm.setStatusId(3);
            boolean success = farmsService.updateById(farm);
            
            if (success) {
                log.info("农场申请已拒绝 - farmId: {}", farmId);
                return R.success("已拒绝农场申请");
            } else {
                log.error("更新农场状态失败 - farmId: {}", farmId);
                return R.error("拒绝申请失败");
            }
        } catch (Exception e) {
            log.error("处理农场拒绝申请失败", e);
            return R.error("拒绝申请处理异常：" + e.getMessage());
        }
    }

    @GetMapping("/detail/{farmId}")
    public R getFarmDetail(@PathVariable Integer farmId, @RequestParam Integer userId) {
        log.info("获取农场详情, farmId: {}, userId: {}", farmId, userId);
        
        try {
            // 1. 获取农场基本信息
            Farms farm = farmsService.getById(farmId);
            if (farm == null) {
                return R.error("农场不存在");
            }
            
            // 验证用户权限
            if (!userId.equals(farm.getUserId())) {
                log.warn("用户ID与农场所有者不匹配, userId: {}, farmUserId: {}", userId, farm.getUserId());
                return R.error("无权查看该农场详情");
            }
            
            // 2. 获取农场图片
            List<String> images = farmsService.getFarmImages(farmId);
            
            // 3. 组装返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("farmInfo", farm);
            result.put("images", images);
            
            log.info("成功获取农场详情");
            return R.success("获取农场详情成功", result);
        } catch (Exception e) {
            log.error("获取农场详情失败", e);
            return R.error("获取农场详情失败：" + e.getMessage());
        }
    }

    @PostMapping("/reapply")
    public R reapplyFarm(@RequestParam("farmId") Integer farmId, 
                        @RequestParam("userId") Integer userId,
                        HttpSession session) {
        log.info("开始处理重新提交申请请求, farmId: {}, userId: {}", farmId, userId);
        
        // 验证用户登录状态
        Integer currentUserId = (Integer) session.getAttribute("userId");
        if (currentUserId == null) {
            log.warn("用户未登录");
            return R.error("用户未登录");
        }
        
        // 验证用户身份
        if (!currentUserId.equals(userId)) {
            log.warn("用户ID不匹配, 当前用户: {}, 请求用户: {}", currentUserId, userId);
            return R.error("无权进行此操作");
        }

        try {
            // 获取农场信息
            Farms farm = farmsService.getById(farmId);
            if (farm == null) {
                log.warn("农场不存在, farmId: {}", farmId);
                return R.error("农场不存在");
            }

            // 验证农场所有权
            if (!userId.equals(farm.getUserId())) {
                log.warn("农场所有者不匹配, 农场所有者: {}, 请求用户: {}", farm.getUserId(), userId);
                return R.error("无权操作此农场");
            }

            int rows = farmsMapper.reapplyFarm(farmId, userId);
            if (rows > 0) {
                log.info("重新提交申请成功 - farmId: {}", farmId);
                return R.success("重新提交申请成功");
            } else {
                log.warn("重新提交申请失败 - farmId: {}", farmId);
                return R.error("重新提交申请失败，请确认农场信息");
            }
        } catch (Exception e) {
            log.error("重新提交申请处理异常", e);
            return R.error("重新提交申请失败：" + e.getMessage());
        }
    }

    @PostMapping("/update/{farmId}")
    public R updateFarm(@PathVariable Integer farmId,
                       @RequestParam(required = false) String farmName,
                       @RequestParam(required = false) String farmAddress,
                       @RequestParam(required = false) String farmDescription,
                       @RequestParam(required = false) MultipartFile[] newImages,
                       @RequestParam(required = false) List<String> deletedImageUrls,
                       HttpSession session) {
        log.info("开始处理更新农场信息请求, farmId: {}", farmId);
        
        // 验证用户登录状态
        Integer currentUserId = (Integer) session.getAttribute("userId");
        if (currentUserId == null) {
            log.warn("用户未登录");
            return R.error("用户未登录");
        }

        try {
            // 获取农场信息
            Farms farm = farmsService.getById(farmId);
            if (farm == null) {
                return R.error("农场不存在");
            }

            // 验证农场所有权
            if (!currentUserId.equals(farm.getUserId())) {
                return R.error("无权修改此农场信息");
            }

            // 更新基本信息
            if (farmName != null) farm.setFarmName(farmName);
            if (farmAddress != null) farm.setFarmAddress(farmAddress);
            if (farmDescription != null) farm.setFarmDescription(farmDescription);

            // 处理图片更新
            List<String> newImageUrls = new ArrayList<>();
            if (newImages != null && newImages.length > 0) {
                for (MultipartFile image : newImages) {
                    String imageUrl = aliOssUtil.upload(image);
                    newImageUrls.add(imageUrl);
                }
            }

            // 调用 Service 层更新农场信息
            boolean success = farmsService.updateFarmInfo(farm, newImageUrls, deletedImageUrls);
            
            if (success) {
                return R.success("更新农场信息成功");
            } else {
                return R.error("更新农场信息失败");
            }
        } catch (Exception e) {
            log.error("更新农场信息失败", e);
            return R.error("更新农场信息失败：" + e.getMessage());
        }
    }
}
